package com.tvunetworks.center.device.service.impl;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tvunetworks.center.common.model.FeatureStatusInfo;
import com.tvunetworks.center.common.model.SendMsgToMsgpipeParam;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.device.constant.DeviceConstant;
import com.tvunetworks.center.device.model.router.Connection;
import com.tvunetworks.center.device.model.router.Peer;
import com.tvunetworks.center.device.model.router.SlotExtend;
import com.tvunetworks.center.device.service.DeviceService;
import com.tvunetworks.center.device.service.RouterService;
import com.tvunetworks.center.device.service.feign.MsgpipeFeignService;
import com.tvunetworks.center.device.service.feign.TpcFeignService;
import com.tvunetworks.center.device.service.feign.UserFeignService;
import com.tvunetworks.center.device.util.HttpClientKeepAliveUtil;
import com.tvunetworks.center.device.util.StringUtil;
import com.tvunetworks.center.device.util.XmlToPeer;
import com.tvunetworks.center.gs.model.BatteryInfo;
import com.tvunetworks.center.gs.model.Device;
import com.tvunetworks.crawler.model.T;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import net.spy.memcached.MemcachedClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
 * @program: tvucc-device
 * @description: ReceiverControlServiceImpl
 * @author lebronchen
 * @create: 2019-03-15 13:22
 **/
@Slf4j
@Service
public class RouterServiceImpl implements RouterService {
    @Autowired
    @Qualifier("tpdsMemcacheClient")
    private MemcachedClient tpdsMemcacheClient;
    @Autowired
    private UserFeignService userFeignService;
    @Autowired
    private DeviceService deviceService;
    @Resource(name = "redisDevTemplate")
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private HttpClientKeepAliveUtil httpClientKeepAliveUtil;
    @Value("${keyListStatus}")
    private String keyListStatus;
    @Value("${slotsStatusKey}")
    private String slotsStatusKey;
    @Value("${rediskeyTimeout}")
    private Long rediskeyTimeout;
    @Value("${updateRouterTime}")
    private String updateRouterTime;
    @Value("${updateRouterIp}")
    private String updateRouterIp;
    @Value("${statusPort}")
    private String statusPort;
    @Value("${appkey}")
    private String appkey;
    @Value("${appsecret}")
    private String appsecret;
    @Value("${routerCenterRul}")
    private String routerCenterRul;
    @Value("${detailInfo}")
    private String detailInfo;
    @Value("${routerServerAuthorization}")
    private String routerServerAuthorization ;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TpcFeignService tpcFeignService;

    @Autowired
    private MsgpipeFeignService msgpipeFeignService;




    @Override
    public List<Peer> findRoutlistfromTPC(String userId) throws Exception {
        List<Peer> peerlist = new ArrayList<>();
        Map<String,Long> routerKeyMap = new HashMap<String,Long>();
        List<Device> listDevice = null;
        try {
            List<String> userDeviceIdList = userFeignService.listUserTids(userId);
            if(userDeviceIdList !=null && userDeviceIdList.size()>0){
                listDevice = deviceService.listCurrentDevice(userDeviceIdList);
            }

//            listDevice = userDeviceService.listPack(getUser().getId(), "0","1", "2", "3");
        } catch (Exception e) {
            log.error("not login ,user is null or Get listDevice error");
        }
        if (listDevice==null || listDevice.size()==0 ){
            return peerlist;
        }
        Map deviceMap = new HashMap<>();
        List<String> peerIds = new ArrayList<String>();
        for(int i=0;i<listDevice.size();i++){
            Device device = listDevice.get(i);
            peerIds.add(device.getPeerId());
            deviceMap.put(device.getPeerId(),device.getName());
        }
        List<String> filterByT = null;
        try {
            FeatureStatusInfo featureStatusInfo = new FeatureStatusInfo();
            featureStatusInfo.setFeatureName("Router");
            featureStatusInfo.setPeerIdList(peerIds);
            Result<FeatureStatusInfo> result =tpcFeignService.getFeatureStatusInfo(featureStatusInfo);
            filterByT=result.getResult().getPeerIdList();
//            filterByT = HttpUtil.getTpcFeatureEnable(configurationUtil.getTpcUrl(), TpcFeature.ROUTER.getName(), peerIds);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        if(filterByT == null || filterByT.size()==0){
            return peerlist;
        }
        for(int i=0;i<filterByT.size();i++){
            String key = DeviceConstant.MemcacheKey.STATUS_FOR_GRIDWITCH+filterByT.get(i);

            try {
                Device o = (Device)tpdsMemcacheClient.get(key);
                if(o==null){
                    continue;
                }
                if("0".equals(o.getStatus())){
                    continue;
                }
            } catch (Exception e) {
                log.error("msg:{},e:{}",e.getMessage(),e);
            }
            Peer peer = new Peer();
            peer.setPeerId(filterByT.get(i));
            peer.setName(deviceMap.get(filterByT.get(i)).toString());

            peerlist.add(peer);
            //初始化当前peer 的redis数据，把key 存入redis ，便于task 根据key 初始化当前peer 的status xml 数据
            String peerkey = "status_xml_"+peer.getPeerId();
            routerKeyMap.put(peerkey,System.currentTimeMillis());
        }
        setRedisKey(routerKeyMap);
        return peerlist;
    }

    private void setRedisKey(Map<String, Long> routerKeyMap) throws Exception {
        if(routerKeyMap.size()>0){
            String routerListKey = keyListStatus;
//            String routerListKey = "keyListStatusPeer";
            //查询当前需要更新routerListKey
            Map<String,Long> routerKeyMapNeedToUpdate =  findKeyNeedToUpadate(routerListKey);
            if(routerKeyMapNeedToUpdate ==null){
                routerKeyMapNeedToUpdate = new HashMap<String,Long>();
            }
            routerKeyMapNeedToUpdate.putAll(routerKeyMap);
            //请求更新 routerKeyMap 存入key
            updateStatusDatas(routerListKey,routerKeyMapNeedToUpdate);

        }
    }

    /**
     *查询需要更新status xml数据的key
     * @param  key key
     * @return Map
     */
    public Map<String,Long> findKeyNeedToUpadate(String key){
        Map<String,Long> routerKeyMaps = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            String result= stringRedisTemplate.opsForValue().get(key);
            if(StringUtils.isNotEmpty(result)){
                routerKeyMaps = mapper.readValue(result,Map.class);
            }else {
                routerKeyMaps = new HashMap<>();
            }

        } catch (Exception e) {
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        return routerKeyMaps;
    }
    /**
     *更新对应key的status xml数据
     * @param key key
     * @param   routerKeyMap routerKeyMap
     * @throws Exception 编译异常
     */
    public synchronized void updateStatusDatas(String key,Map<String,Long> routerKeyMap) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        stringRedisTemplate.opsForValue().set(key,mapper.writeValueAsString(routerKeyMap));
    }

    /**
     *
     * @throws Exception 编译异常
     */
    public void getStatusXmlTask() throws Exception{
//        System.out.println("==========getStatusXmlTask start=======");
        Long timeOutFlag = rediskeyTimeout;
        String routerListKey = keyListStatus;
//        String routerListKey = "keyListStatusPeer";
        Map<String,Long> routerKeyMap = findKeyNeedToUpadate(routerListKey);
        Map<String,Long> routerKeyMapUpdate = new HashMap<String,Long>();
        List routerKeyToUpdateList = new ArrayList();
        //获取需要更新的key集合
        if(routerKeyMap==null){
            return;
        }
        for (Map.Entry<String, Long> entry : routerKeyMap.entrySet()){
            String key = entry.getKey();
            Long value = entry.getValue();
//            java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
//            System.out.println(key+":创建时间:"+sdf.format(value));
            Long re = System.currentTimeMillis()-value;
            //如果key未超时
            if(re<timeOutFlag*1000){
                routerKeyToUpdateList.add(key);
                routerKeyMapUpdate.put(key,value);
            }
        }
        if(routerKeyToUpdateList.size()>0){
            //删除超时的key后更新到redis,保证redis中redisMap 中都是未超时的key
            updateStatusDatas(routerListKey,routerKeyMapUpdate);
            //需要及时更新数据的key，同步status xml
            savePeerXMLtoRedis(routerKeyToUpdateList);
        }
    }



    /**
     * 保存peerxml 到redis
     * @param routerKeyToUpdateList routerKeyToUpdateList
     * @throws Exception 编译异常
     */
    private void savePeerXMLtoRedis(List routerKeyToUpdateList) throws Exception {
        log.info("===routerKeyToUpdateList size=="+ JsonUtil.toJsonStr(routerKeyToUpdateList));
        for(int i=0;i<routerKeyToUpdateList.size();i++){
            try{
                String key = routerKeyToUpdateList.get(i).toString();
                log.info("savePeerXMLtoRedis key:{}",key);
                String peerXML = "";
                String[] keyArray = key.split("_");
                if(keyArray == null || keyArray.length < 3){
                   log.info("savePeerXMLtoRedis data format is error,i:{}",i,key);
                   //continue;
                }
                //通过接口获取peerXML
                String routerKeyTime = "T_"+updateRouterTime+keyArray[2];
                String routerKeyIp = updateRouterIp+keyArray[2];
                String lastTimeValue = stringRedisTemplate.opsForValue().get(routerKeyTime);
                Long lastTime = 0L;
                if(StringUtils.isNotBlank(lastTimeValue)){
                    lastTime = Long.parseLong(lastTimeValue);
                }
                log.info("savePeerXMLtoRedis get lastTime is:{},i:{},key:{}",i,lastTime,key);
                String routerIp ="";
                if(System.currentTimeMillis()-lastTime>10000){
                    log.info("savePeerXMLtoRedis get keyArray[2] is:{}",keyArray[2]);
                    routerIp = getRouterAuthIp(keyArray[2]);
                    log.info("savePeerXMLtoRedis get routerIp is:{}",routerIp);
                    //定义key 是否需要调用router center接口，超过5秒钟调一次 update_Router_Ip_tid
                    stringRedisTemplate.opsForValue().set(routerKeyTime,System.currentTimeMillis()+"");
                    stringRedisTemplate.opsForValue().set(routerKeyIp,routerIp);
                }else{
                    routerIp = stringRedisTemplate.opsForValue().get(routerKeyIp);
                    log.info("savePeerXMLtoRedis stringRedisTemplate.opsForValue().get routerIp is:{}",routerIp);
                }
                log.info("savePeerXMLtoRedis get routerIp is:{} by key:{}",routerIp,key);
                if (StringUtils.isEmpty(routerIp)) {
                    //当无法从router center 获取ip或者域名时,清空之前的数据
//                redisShardPool.del(key);
                    stringRedisTemplate.opsForValue().set(key,"");
                    continue;
                }
                String url = "http://" + routerIp + ":" + statusPort + "/status";
                try {
                    peerXML = httpClientKeepAliveUtil.sendGet(url,null,routerServerAuthorization);
                } catch (Exception e) {
                    log.error("==HttpClientUtils.sendRequest获取peerXML异常==class:PageRouterWebsocket.java;method:findPeerMsg();line:163;param:" + url);
                }
                log.info("savePeerXMLtoRedis get peerXML is:{} by key:{}",peerXML,key);
                //保存xml
                savaJsonToRedis(key, peerXML);
                //更新peer slot 状态
//            sendMsgPipeToQuerySlotStatus(key);
            }catch (Exception e){
                log.info("savePeerXMLtoRedis is error by i:{},error",i,e);
            }
        }
    }
    /**
     * 通过调用routerCenter 获取Ip
     * @param pid pid
     * @return String
     * @throws Exception 编译异常
     */
    public String getRouterAuthIp(String pid) throws Exception{
        Long timestamp = System.currentTimeMillis();
        String  jsonData = "";
        String signature =  StringUtil.MD5(appsecret+timestamp);
//        String signature =  StringUtil.MD5("d9aa5247ff9336c95b7941604d987f6a"+timestamp);
        StringBuffer routerCenterUrl = new StringBuffer();
        routerCenterUrl.append(routerCenterRul);
        routerCenterUrl.append("/SelectInstanceServlet/getInstanceByPid?appkey="+appkey);
//        routerCenterUrl.append("/SelectInstanceServlet/getInstanceByPid?appkey=d8e8560b4df405f1e7580262b4652008");
        routerCenterUrl.append("&signature="+signature);
        routerCenterUrl.append("&timestamp="+timestamp);
        routerCenterUrl.append("&pId="+pid);
        //调用routerCerter
        String result = null;
        try {
            log.error("ROUTER center Request URL:"+routerCenterUrl);
//            result = HttpClientUtils.sendRequest(routerCenterUrl.toString());
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(routerCenterUrl.toString(), String.class);
            result = responseEntity.getBody();
            log.error("==HttpClientUtils.sendRequest()获取结果"+result);
            log.info("ROUTER center Request result:"+result);
        } catch (Exception e) {
            log.error("==HttpClientUtils.sendRequest()获取router ip失败==CLASS:PageRouterWebsocket.java;method:getRouterAuthIp();line:264;param:"+routerCenterUrl.toString());
            log.error("==HttpClientUtils.sendRequest()",e);
        }
        if(StringUtils.isEmpty(result)){
            return jsonData;
        }
        if(!result.startsWith("{")){
            return jsonData;
        }
        JSONObject json = JSONObject.fromObject(result);
        if(json == null){
            return jsonData;
        }
        Object dataObj = json.get("data");
        if(dataObj == null){
            return jsonData;
        }
        String dataStr = dataObj.toString();
        if(StringUtils.isBlank(dataStr)){
            return jsonData;
        }
        //get router ip from json message
        jsonData = JSONObject.fromObject(dataStr).get("ip").toString();
        return jsonData;
    }
    /**
     * jsonObject 保存至redis
     * @param key key
     * @param peerXML peerXML
     * @throws Exception 编译异常
     */
    public void savaJsonToRedis(String key, String peerXML) throws Exception{
        JSONObject objectset = new JSONObject();
        objectset.put("peerXML",peerXML);
        ObjectMapper mapper = new ObjectMapper();
        stringRedisTemplate.opsForValue().set(key, mapper.writeValueAsString(objectset),10,TimeUnit.SECONDS);

    }

    @Override
    public String findSlotsCheckStatus(String peerId) throws Exception {
        String key = slotsStatusKey+peerId;
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public String getRouterSelectRecord(String userid) {
        return stringRedisTemplate.opsForValue().get(userid);
    }

    @Override
    public void sendMsgPipe(String peerId, String slotId, String cmd, Long timestamp) throws Exception {
        String isabled = "enabled";
        if("STOP".equals(cmd)){
            isabled="disabled";
        }
        String url = "/control/selectLocalSlots.do?format=json&remotePeerId="+peerId+"&slot"+slotId+"="+isabled;

        JSONObject object = new JSONObject();
        object.put("timestamp",timestamp);
        object.put("peerid",peerId);
        object.put("cmd",cmd);
        object.put("slotid",slotId);
        object.put("target","router");
        object.put("url",url);
        if("RESET".equals(cmd)){
            object.put("type","RESET");
        }else if("START".equals(cmd)){
            object.put("type","START");
        }else{
            object.put("type","STOP");
        }
        String msgbody = JsonUtil.toJsonStr(object);
        String msghead="{\"EventId\":0,\"TimeStamp\":0,\"Type\":605,\"Ver\":0,\"Zip\":false,\"Sender\":\"0x0000000100000021\",\"Recipient\":[\""+peerId.toUpperCase()+"\"],\"MsgBodyLen\":"+msgbody.length()+",\"Key\":0}";
        StringBuffer msgBuffer= new StringBuffer();
        msgBuffer.append(msghead);
        msgBuffer.append(msgbody);
        SendMsgToMsgpipeParam sendMsgToMsgpipeParam = new SendMsgToMsgpipeParam();
        sendMsgToMsgpipeParam.setBooking(false);
        sendMsgToMsgpipeParam.setMsgBody(msgbody);
        sendMsgToMsgpipeParam.setReceiver(peerId.toUpperCase());
        sendMsgToMsgpipeParam.setType(605);
        sendMsgToMsgpipeParam.setBatchReceiver(false);
        msgpipeFeignService.sendMsgToMsgpipe(sendMsgToMsgpipeParam);
        log.info("==msgpipe 发送消息给T开始==Class:RouterAction;method:sendMsgPipe;Line:138;params:"+msgBuffer.toString());
//        webSocketClientUtil.sendMsgToRouter(msgBuffer.toString());//todo
        addSlotKeyToList(peerId);

    }

    @Override
    public String findSlotsMsg(String type, String module, String tid) throws Exception {
        JSONObject object = new JSONObject();
        Map connectMap =  new HashMap();
        object.put("module",module);
        object.put("type",type);
        String keys = "status_xml_"+tid;
        try {
            Map<String,Long> routerKeyMap = new HashMap<String,Long>();
            routerKeyMap.put(keys,System.currentTimeMillis());
            setRedisKey(routerKeyMap);
        } catch (Exception e) {
            log.error("===================findSlotsMsg==========:", e);
        }
        //从psMemcachedClient获取TT对象中的Slots信息
//        TT peer = null;
        T t= null;
        T.TIME time = null;
        List<T.TIME.SLOT> slots = null;
        try {
            String str = stringRedisTemplate.opsForValue().get(detailInfo+tid.toLowerCase());//tpds cralwer redis 获取
            t = JSON.parseObject(str,T.class);
            int slotSize =t.getTIME().size();
            time = t.getTIME().get(slotSize-1);
            slots = time.getSLOT();
//            peer = (TT)psMemcachedClient.get("t_detail_info_4_tpc_"+tid);
            System.out.println("");
        } catch (Exception e) {
            log.error("==从psMemcachedClient获取TT对象中的Slots信息失败==CLASS:PageRouterWebsocket;method:findSlotsMsg;line:103;param:");
        }
        JSONObject peerObject = getStatusXMLJson(keys);
        String   peerXML = "";
        if(peerObject !=null && peerObject.size()>0){
            peerXML = peerObject.get("peerXML").toString();
        }
        List<Peer> peerList = null;
        try {
//            logger.error("=====class:PageRouterWebsocket.java;method:findPeerMsg();line:174;param:"+peerXML);
            if(StringUtils.isNotEmpty(peerXML)){
                peerList = XmlToPeer.xmlToPeer(peerXML);
                if(peerList !=null && peerList.size()>0 ){
                    for (Peer peer:peerList){
                        if(peer.getPeerId().toLowerCase().contains(tid.toLowerCase())){
                            List<Connection> connectionList = peer.getConnectionList();
                            for (Connection connection:connectionList){
                                connectMap.put(connection.getRemoteSlotId(),connection.getRttInMsec());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("==PeerXML转换异常==class:PageRouterWebsocket.java;method:findPeerMsg();line:174;param:"+peerXML);
        }
        if(slots ==null || slots.size()==0){

            object.put("id","");
            object.put("newestTotalSpeeds","");
            object.put("tStatusNewestTime","");
            object.put("name","");
            object.put("tID","");
            object.put("slots","");
            object.put("cops","");
            object.put("csq","");
            object.put("rtt","");
        }else {
            object.put("id", t.getID());
            object.put("newestTotalSpeeds", "");
            List slotList = new ArrayList();
            for ( T.TIME.SLOT slot : slots) {
                SlotExtend slotExtend = new SlotExtend();
                slotExtend.setId(slot.getID());
                slotExtend.setType(slot.getTYPE());
                slotExtend.setInet(slot.getINET());
                slotExtend.setIp(slot.getIP());
                slotExtend.setPs(slot.getPS());
                slotExtend.setSpeed(slot.getSPEED());
                slotExtend.setCops(slot.getCops());
                slotExtend.setCsq(slot.getCsq());
                //设置RTT信息
                if("0".equals(slot.getID())){
                    if(connectMap.containsKey("11")){
                        slotExtend.setRtt(connectMap.get("11").toString());
                    }else{
                        slotExtend.setRtt("0");
                    }

                }else{
                    if(connectMap.containsKey(slot.getID())) {
                        slotExtend.setRtt(connectMap.get(slot.getID()).toString());
                    }else{
                        slotExtend.setRtt("0");
                    }
                }
                //获取slot checkstatus
                String peerId = t.getID().toLowerCase();
                if(peerId.startsWith("0x")){
                    peerId=peerId.substring(2);
                }
                String key = slotsStatusKey+"_selectSlots_"+peerId+"_"+slot.getID();
                String checkstatus = stringRedisTemplate.opsForValue().get(key);
                if(StringUtils.isNotEmpty(checkstatus)){
                    JSONObject slotsObject = JsonUtil.toObject(checkstatus,JSONObject.class);
                    JSONObject ret = JsonUtil.toObject(slotsObject.get("ret").toString(),JSONObject.class);
                    JSONObject result = JsonUtil.toObject(ret.get("result").toString(),JSONObject.class);
                    String error = result.get("error").toString();
//                    String reason = result.get("reason").toString();
                    if("succeeded".equals(error)){
                        slotExtend.setCheckStatus("true");
                    }else {
                        slotExtend.setCheckStatus("false");
                    }
                }
                slotList.add(slotExtend);

            }
            if(slotList.size()>0){
//                JSONArray json = JsonUtil.toObject(slotList,JSONArray.class);
                object.put("slots", slotList);
            }else{
                object.put("slots", "");
            }
            object.put("tStatusNewestTime", time.getT());
            object.put("name", t.getNAME());
            object.put("tID", t.getID());

        }
        String jsonArray =JsonUtil.toJsonStr(object);
        return jsonArray;
    }

    @Override
    public String findPeerMsg(String type, String module, String tid, String userid) throws Exception{
        //保存router选择记录
        String recordKey = userid;
        String recordid = stringRedisTemplate.opsForValue().get(recordKey);
        if(!tid.equals(recordid) && StringUtils.isNotEmpty(userid)){
//            Long delResult = redisShardPool.del(recordKey);
            stringRedisTemplate.opsForValue().set(recordKey,tid);
//            System.out.println(delResult+":"+setResult);
        }
//        tid = "9B9E3BEDB0426E75";
        String key = "status_xml_"+tid;
        Map object = new HashMap();
        object.put("type",type);
        object.put("module",module);

        //读取redis  获取peerXML
        JSONObject peerObject = getStatusXMLJson(key);
        String   peerXML = "";
        if(peerObject !=null && peerObject.size()>0){
            peerXML = peerObject.get("peerXML").toString();
        }
//        System.out.println("===========findPeerMsg peerXML is :"+peerXML);
        BatteryInfo batteryInfo = getBatteryInfo(tid);
        if(StringUtils.isEmpty(peerXML)){
            getPeerObject(tid, object, null);
            return JsonUtil.toJsonStr(object);
        }
        // xml to peerList
        List<Peer> peerList = null;
        try {
//            logger.error("=====class:PageRouterWebsocket.java;method:findPeerMsg();line:174;param:"+peerXML);
            peerList = XmlToPeer.xmlToPeer(peerXML);
        } catch (Exception e) {
            log.error("==PeerXML转换异常==class:PageRouterWebsocket.java;method:findPeerMsg();line:174;param:"+peerXML);
            getPeerObject(tid, object, null);
            return JsonUtil.toJsonStr(object);
        }

        boolean flag = false;
        if (peerList !=null&&peerList.size()>0){
            for(int i =0;i<peerList.size();i++){
                Peer peer = peerList.get(i);
                String peerid = peer.getPeerId();
                //去掉0x 开头
                if(peerid.startsWith("0x")){
                    peerid=peerid.substring(2).toLowerCase();
                }
                if(tid.toLowerCase().equals(peerid)){

//                if("78A188EB946131DC".toLowerCase().equals(peerid)) {
                    flag =true;

                    Device device = deviceService.getCurrentDevice(tid);
                    if(device==null){
                        device = deviceService.getCurrentDevice(tid);
                    }
                    peer.setBatteryInfo(batteryInfo);
                    peer.setPlatform(device.getPlatform());
                    peer.setStatus(device.getStatus());
                    object.put("peer",peer);
                    break;
                }
            }
        }
        if(!flag){
            getPeerObject(tid, object, batteryInfo);
        }
        String jsonArray =JsonUtil.toJsonStr(object);
        updatKeyTime(key);
        return jsonArray;
    }

    @Override
    public String routerStatus(String type, String module, String tid, String userid) throws Exception {
        String routerIp = getRouterAuthIp(tid);
        JSONObject object = new JSONObject();
        object.put("module",module);
        object.put("type",type);
        if (StringUtil.isNullEmp(routerIp)){
            object.put("connected","false");
        }else {
            object.put("connected","true");
        }
        return JsonUtil.toJsonStr(object);
    }

    private void updatKeyTime(String key) throws Exception{
        //请求更新 routerKeyMap 存入key
        String routerListKey = keyListStatus;
//        String routerListKey = "keyListStatusPeer";
        //获取routerKeyMap 并添加当前key或者更新当前key的timestamp
        Map<String,Long> routerKeyMap = findKeyNeedToUpadate(routerListKey);
        if(routerKeyMap == null){
            routerKeyMap =  new HashMap<String,Long>();
        }
        routerKeyMap.put(key,System.currentTimeMillis());
        ObjectMapper mapper = new ObjectMapper();
        stringRedisTemplate.opsForValue().set(routerListKey,mapper.writeValueAsString(routerKeyMap));
    }
    /**
     * 从redis中获取数据
     * @param key key
     * @return JSONObject
     * @throws Exception 编译异常
     */
    public JSONObject getStatusXMLJson(String  key) throws Exception{
        String jsonObject = stringRedisTemplate.opsForValue().get(key);
        JSONObject object = new JSONObject();
        if(StringUtils.isNotEmpty(jsonObject)){
            object= JsonUtil.toObject(jsonObject,JSONObject.class);
        }
        return object;
    }

    @Override
    public String querySlotStatus(String tid) {
        return null;
    }

    /**
     *将peerid 存入redis,用于定时任务同步slots信息
     * @param peerId peerId
     * @throws Exception 编译异常
     */
    public void addSlotKeyToList(String peerId) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        String key = "slots_key_list";
        //查询slots key list 并加入新的
        Map<String,String> slotKeyMaps = new HashMap<>();
        String result = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(result)){
            slotKeyMaps = mapper.readValue(result,Map.class);
        }

        slotKeyMaps.put(peerId,peerId);
        //更新或者存入redis

        stringRedisTemplate.opsForValue().set(key,mapper.writeValueAsString(slotKeyMaps));
    }
    /**
     * get Battery message
     * @param pid pid
     * @return (BatteryInfo) ccMemcachedClient.get(configurationUtil.getBatteryForSource() + device.getPeerId().toLowerCase())
     * @throws Exception 编译异常
     */
    public BatteryInfo getBatteryInfo(String pid){
        BatteryInfo batteryInfo = null;
        try {
//            batteryInfo = (BatteryInfo)ccMemcachedClient.get(configurationUtil.getBatteryForSource()+pid.toLowerCase());
            String detailInfos = stringRedisTemplate.opsForValue().get(detailInfo+pid.toLowerCase());
            if(StringUtils.isNotEmpty(detailInfos)){
                T t = JsonUtil.toObject(detailInfos,T.class);
                T.BATTERY battery = t.getBattery();
                if(battery !=null){
                    String batteryInfostr =JsonUtil.toJsonStr(battery);
                    batteryInfo = JsonUtil.toObject(batteryInfostr,BatteryInfo.class);
                }
            }
        } catch (Exception e) {
            log.error("==获取电池电量信息失败==class:PageRouterWebsocket.java;method:getBatteryInfo();line:244;param:"+pid.toLowerCase());
        }
        return batteryInfo;
    }
    /**
     * 当没有在线的peer时 拼装JSONObject
     * @param tid tid
     * @param object object
     * @param batteryInfo batteryInfo
     */
    private void getPeerObject(String tid, Map object, BatteryInfo batteryInfo) {

        Peer peer = new Peer();
        Device device = deviceService.getCurrentDevice(tid);
        if(device == null){
            device = deviceService.getCurrentDevice(tid);
        }
        if(device !=null){
            peer.setStatus(device.getStatus());
            peer.setPlatform(device.getPlatform());
            peer.setName(device.getName());
        }else{
            peer.setStatus("");
            peer.setPlatform("");
            peer.setName("");
        }
        peer.setPeerId(tid);
        peer.setBatteryInfo(batteryInfo);
        peer.setClientList(null);
        peer.setConnected("");
        peer.setConnectedTimeInSeconds("");
        peer.setConnectionList(null);
        peer.setReceivedBytesInSession("");
        peer.setReceivedRepairPacketsNum("");
        peer.setReceivedSourcePacketsNum("");
        peer.setSentBytesInSession("");
        object.put("peer",peer);
    }

    /**
     * 查询slot状态
     * @param peerId peerId
     */
    @Override
    public void sendMsgPipeToQuerySlotStatus(String peerId) throws Exception{
        String url = "/control/queryLocalSlots.do?format=json&remotePeerId="+peerId;
        Long timestamp = System.currentTimeMillis();
        Map object = new HashMap();
        object.put("timestamp",timestamp);
        object.put("peerid",peerId);
        object.put("target","router");
        object.put("url",url);
        object.put("type","querySlots");
        String msgbody = JsonUtil.toJsonStr(object);
        String msghead="{\"EventId\":0,\"TimeStamp\":0,\"Type\":605,\"Ver\":0,\"Zip\":false,\"Sender\":\"0x0000000100000021\",\"Recipient\":[\""+peerId.toUpperCase()+"\"],\"MsgBodyLen\":"+msgbody.length()+",\"Key\":0}";
        StringBuffer msgBuffer= new StringBuffer();
        msgBuffer.append(msghead);
        msgBuffer.append(msgbody);
//        webSocketClientUtil.sendMsgToRouter(msgBuffer.toString());
    }
    /**
     * 保存slots check status 到redis
     * @param slotsJson slotsJson
     */
    public void saveSlotsStatusToRedis(String slotsJson){
        JSONObject slotsObject = JSONObject.fromObject(slotsJson);
        String peerid = slotsObject.getString("localPeerId");
        String type = slotsObject.getString("type");
        String timestamp = slotsObject.getString("timestamp");
        if(StringUtils.isEmpty(peerid)){
            return;
        }else{
            if(peerid.startsWith("0x")){
                peerid = peerid.substring(2).toLowerCase();
            }
        }
        String key = "";
        String ret = slotsObject.getString("ret");
        if(type.equals("RESET")){
            //保存selectSlots信息
            key = slotsStatusKey+"_RESET_"+peerid+"_"+timestamp;
            stringRedisTemplate.opsForValue().set(key,ret,10, TimeUnit.SECONDS );
            return;
        }else if(type.equals("STOP")){
            key = slotsStatusKey+"_STOP_"+peerid+"_"+timestamp;
            stringRedisTemplate.opsForValue().set(key,ret,10,TimeUnit.SECONDS);
            return;
        }else if(type.equals("START")){
            key = slotsStatusKey+"_START_"+peerid+"_"+timestamp;
            stringRedisTemplate.opsForValue().set(key, ret,10,TimeUnit.SECONDS);
            return;
        }else {
            //保存querySlots信息
            key = slotsStatusKey+"_querySlots_"+peerid;
        }
        try {
//            logger.error("==保存slotsJson到redis==CLASS:RouterServiceImple.java;method:saveSlotsStatusToRedis;line:155;params:key="+key+";slotsJson="+slotsJson);
            stringRedisTemplate.opsForValue().set(key, slotsJson);
        } catch (Exception e) {
            log.error("==保存slotsJson到redis发生异常==CLASS:RouterServiceImple.java;method:saveSlotsStatusToRedis;line:155;params:key="+key+";slotsJson="+slotsJson+";ERROR:"+e.getMessage().toString());
        }
    }
}
